package org.jvending.provisioning.adapter;

import javax.provisioning.Deliverable;
import javax.provisioning.DeliveryComponent;
import javax.provisioning.DeliveryContext;
import javax.provisioning.DescriptorFile;
import javax.provisioning.adapter.Adapter;
import javax.provisioning.adapter.AdapterContext;
import javax.provisioning.adapter.AdapterException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;

public class MavenAdapterServlet extends HttpServlet {

    private final static int POM_REQUEST = 0;

    private final static int PRIMARY_ARTIFACT_REQUEST = 1;

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String fulfillmentId = request.getParameter("fid");
        System.out.println("MavenAdapterServlet");
        if (fulfillmentId == null) throw new IOException("JV: No FulfillmentID. Can not process request");

        AdapterContext adapterContext =
                (AdapterContext) this.getServletContext().getAttribute("javax.provisioning.ProvisioningContext");
        DeliveryComponent deliveryComponent = adapterContext.getDeliveryComponent();
        DeliveryContext deliveryContext = adapterContext.getDeliveryContext(request);
        Adapter adapter = adapterContext.getAdapter("mvnd");
        DescriptorFile descriptorFile;
        try {
            descriptorFile = adapter.createDescriptorFile(new URL(request.getRequestURL().append("?")
                    .append(request.getQueryString()).toString()));
        } catch (AdapterException e) {
            e.printStackTrace();
            throw new IOException("JV: Could not create a DescriptorFile: " + e.getMessage());
        }

        Deliverable outputDeliverable = null;
        for (Deliverable deliverable : descriptorFile.getContentFiles()) {
            if(request.getParameter("mimeType").equals(deliverable.getMimeType()))
            {
                outputDeliverable = deliverable;
            }
        }
        response.setContentType(outputDeliverable.getMimeType());

        try {
            outputDeliverable.writeContents(response.getOutputStream());
        } finally {
            response.getOutputStream().close();
        }
    }
}
